import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Row,
  Col,
  message,
  Modal,
  Text,
  Icon,
  Table,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import { progType, progSpeed, progEntrAnimat, progExitAnimat } from '../../utils/city';
import SelectMat from '../../components/UpLoadForm/SelectMat';
import SelectArea from '../../components/UpLoadForm/SelectArea';

import Styles from './BasicList.less';
import { Label } from 'rc-bmap';

let id = 1;
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

@connect(({ rule, program, areaInfo, loading }) => ({
  rule,
  program,
  areaInfo,
  submitting: loading.effects['program/addProgramMat'],
}))
@Form.create()
export default class BasicForms extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      areaVisible: false,
      matId: '',
      matName: '',
      selectArea: [],
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'rule/fetch',
      payload: { matAuditStatus: 1 }, // 仅获取已经审核通过的
    });
    this.props.dispatch({
      type: 'areaInfo/fetch',
    });
    this.props.dispatch({
      type: 'rule/fetchMatTime',
      payload: {},
    });
    this.props.dispatch({
      type: 'areaInfo/fetchType',
    });
    this.props.dispatch({
      type: 'areaInfo/fetchShape',
    });
  }

  setVisible = value => {
    this.setState({
      modalVisible: value,
    });
  };
  setAreaVisible = value => {
    this.setState({
      areaVisible: value,
    });
  };
  setMatId = (value, name) => {
    this.setState({
      matId: value,
      matName: name,
    });
  };
  setArea = value => {
    this.setState({
      selectArea: value,
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let tiSlotId = '';
        let startTimeArray = [];
        let endTimeArray = [];
        let startDate = '';
        let endDate = '';
        if (Array.isArray(values.rangeTime)) {
          //选择了多个时段
          tiSlotId = values.rangeTime.join(',');
        }
        let dateRange = values.date;
        if (Array.isArray(dateRange)) {
          startDate = dateRange[0].format('YYYY-MM-DD');
          endDate = dateRange[1].format('YYYY-MM-DD');
        }

        const { progId } = this.props.match.params;
        const { matId } = this.state;
        if (matId === '') {
          message.error('请选择素材');
        } else {
          const jsonCont = {
            ...values,
            matId,
            startDate,
            endDate,
            tiSlotId,
            progId,
          };
          delete jsonCont.date;
          const { selectArea } = this.state;
          if (selectArea.length > 0) {
            let playAreaIds = selectArea.map(item => item.areaId).join(',');
            jsonCont.playAreaIds = playAreaIds;
          }
          // console.log('values', jsonCont);
          this.props.dispatch({
            type: 'program/addProgramMat',
            payload: { jsonCont },
            callback: () => {
              message.success('添加素材成功');
              // const encodeName = encodeURI(progName);
              this.props.history.push(`/program/programconfig/${progId}`);
            },
          });
        }
      }
    });
  };
  FormSelect = (name, label, options, initialValue = 0) => {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <FormItem {...formItemLayout} label={label} style={{display:'none'}}>
        {getFieldDecorator(name, {
          rules: [{ required: true, message: `请选择${label}!` }],
          initialValue,
        })(
          <Select placeholder={`请选择${label}!`} onChange={this.handleSelectChange}>
            {options.map((option, index) => (
              <Option value={index} key={index}>
                {option}
              </Option>
            ))}
          </Select>
        )}
      </FormItem>
    );
  };
  render() {
    const {
      submitting,
      rule: { MatTime },
      areaInfo,
    } = this.props;
    //const { getFieldDecorator } = this.props.form;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const columns = [
      {
        title: '区域名称',
        dataIndex: 'areaName',
        editable: true,
      },
      {
        title: '区域类型',
        dataIndex: 'areaType',
      },

      {
        title: '区域形状',
        dataIndex: 'areaShape',
      },

      {
        title: '描述',
        dataIndex: 'shapeDescr',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    return (
      <PageHeaderLayout title="添加素材">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            {/* <FormItem {...formItemLayout} label="类型">
              {getFieldDecorator('playType', {
                initialValue: 0,
              })(
                <Radio.Group>
                  <Radio value={0}>精确排挡（高级）</Radio>
                  <Radio value={1}>简单排挡（高级）</Radio>
                  <Radio value={2}>插播</Radio>
                  <Radio value={3}>安保测试</Radio>
                </Radio.Group>
              )}
            </FormItem> */}
            <FormItem {...formItemLayout} label="播放时间长度（单位:秒）">
              {getFieldDecorator('playTimeLen', {
                initialValue: 20,
                rules: [
                  {
                    required: true,
                    message: '请输入播放时长',
                  },
                ],
              })(<InputNumber style={{ width: '50%' }} placeholder="请输入播放时长" />)}
            </FormItem>
            {this.FormSelect('playSpeed', '播放速度', progSpeed)}
            {this.FormSelect('entrAnimat', '入场动画', progEntrAnimat)}
            {this.FormSelect('exitAnimat', '出场动画', progExitAnimat, 1)}
            <FormItem {...formItemLayout} label="起止日期">
              {getFieldDecorator('date', {
                rules: [
                  {
                    required: false,
                    message: '请选择起止日期',
                  },
                ],
              })(
                <RangePicker
                  style={{ width: '80%' }}
                  mode={['date', 'date']}
                  format="YYYY-MM-DD"
                  placeholder={['开始日期', '结束日期']}
                />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="播放时段">
              {getFieldDecorator('rangeTime', {
                rules: [{ required: false, message: '请选择播放时段...' }],
              })(
                <Select
                  allowClear="true"
                  mode="multiple"
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  {MatTime.map(item => (
                    <Option value={item.code} key={item.code}>
                      {item.timeSlot}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>

            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 14 }} wrapperCol={{ span: 8 }} label="声音" style={{display:'none'}}>
                  {getFieldDecorator('sound', {
                    rules: [{ required: true, message: '选择视频声音是否开启!' }],
                    initialValue: 1,
                  })(
                    <Select placeholder="选择视频声音是否开启">
                      <Option value={0}>无声音</Option>
                      <Option value={1}>有声音</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 8 }} label="帧频" style={{display:'none'}}>
                  {getFieldDecorator('frameRate', {
                    rules: [{ required: true, message: '选择视频频率!' }],
                    initialValue: 15,
                  })(
                    <Select placeholder="选择视频频率">
                      {[...new Array(16).keys()].map(item => (
                        <Option value={item + 15}>{item + 15}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 14 }} wrapperCol={{ span: 8 }} label="播放优先级">
                  {getFieldDecorator('priority', {
                    rules: [{ required: false, message: '播放优先级!' }],
                    initialValue: 2,
                  })(
                    <Select placeholder="选择视频声音是否开启">
                      <Option value={1}>高</Option>
                      <Option value={2}>中</Option>
                      <Option value={3}>低</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <FormItem {...formItemLayout} style={{ marginBottom: 0 }} label="选择素材">
              <Row>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setVisible(true);
                  }}
                >
                  点击添加素材
                </Button>
              </Row>
              <Row>
                <span>{this.state.matName ? this.state.matName : ''}</span>
              </Row>
            </FormItem>
            <FormItem {...formItemLayout} style={{ marginBottom: 0 }} label="选择区域">
              <Row>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setAreaVisible(true);
                  }}
                >
                  点击添加播放区域
                </Button>
              </Row>
              <Row>
                <Table rowKey="AreaId" dataSource={this.state.selectArea} columns={columns}></Table>
              </Row>
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
        <SelectMat
          modalVisible={this.state.modalVisible}
          dispatch={this.props.dispatch}
          rule={this.props.rule}
          handleModalVisible={this.setVisible}
          setMatId={this.setMatId}
        />
        <SelectArea
          modalVisible={this.state.areaVisible}
          dispatch={this.props.dispatch}
          rule={this.props.areaInfo}
          handleModalVisible={this.setAreaVisible}
          setArea={this.setArea}
        />
      </PageHeaderLayout>
    );
  }
}
